#include "include/widgets/login_dialog.hpp"
#include "include/widgets/register_dialog.hpp"

LoginDialog::LoginDialog(TradingSystem *tradingSystem, QWidget *parent)
    : QDialog(parent), m_tradingSystem(tradingSystem) {
  setWindowTitle("登录");
  setFixedSize(300, 200);

  // 创建界面元素
  auto *layout = new QVBoxLayout(this);

  auto *usernameLayout = new QHBoxLayout();
  auto *usernameLabel = new QLabel("用户名:", this);
  usernameLabel->setFixedWidth(60);
  m_usernameEdit = new QLineEdit(this);
  usernameLayout->addWidget(usernameLabel);
  usernameLayout->addWidget(m_usernameEdit);

  auto *passwordLayout = new QHBoxLayout();
  auto *passwordLabel = new QLabel("密码:", this);
  passwordLabel->setFixedWidth(60);
  m_passwordEdit = new QLineEdit(this);
  m_passwordEdit->setEchoMode(QLineEdit::Password);
  passwordLayout->addWidget(passwordLabel);
  passwordLayout->addWidget(m_passwordEdit);

  auto *buttonLayout = new QHBoxLayout();
  m_loginButton = new QPushButton("登录", this);
  m_registerButton = new QPushButton("注册", this);
  buttonLayout->addWidget(m_loginButton);
  buttonLayout->addWidget(m_registerButton);

  layout->addLayout(usernameLayout);
  layout->addLayout(passwordLayout);
  layout->addSpacing(20);
  layout->addLayout(buttonLayout);

  // 连接信号槽
  connect(m_loginButton, &QPushButton::clicked, this,
          &LoginDialog::onLoginClicked);
  connect(m_registerButton, &QPushButton::clicked, this,
          &LoginDialog::onRegisterClicked);

  // 设置Enter键触发登录
  m_loginButton->setDefault(true);
}

void LoginDialog::onLoginClicked() {
  QString username = m_usernameEdit->text().trimmed();
  QString password = m_passwordEdit->text();

  if (username.isEmpty() || password.isEmpty()) {
    QMessageBox::warning(this, "错误", "用户名和密码不能为空");
    return;
  }

  if (m_tradingSystem->loginUser(username, password)) {
    accept();
    emit loginSuccessful();
  } else {
    QMessageBox::critical(this, "登录失败", "用户名或密码错误");
  }
}

void LoginDialog::onRegisterClicked() {
  RegisterDialog registerDialog(m_tradingSystem, this);
  if (registerDialog.exec() == QDialog::Accepted) {
    // 如果注册成功，自动填入用户名
    m_usernameEdit->setText(registerDialog.getUsername());
    m_passwordEdit->setText(registerDialog.getPassword());
  }
}
